#![allow(unused_imports,dead_code,unused_assignments)]
use axum::{
    extract::{Form, Query, Json, Multipart,DefaultBodyLimit},
    routing::{get,post},
    response::Response,
    body::{Body, Bytes},
    Router
};
use chrono::{NaiveDate,NaiveDateTime};
use crate::domain::CustOrderBean;
use crate::domain::CustOrderQueryRequest;
use crate::domain::my_date_format::DATE_FORMAT;
use crate::domain::my_date_time_format::DATE_TIME_FORMAT;

use crate::serviceimpl::cust_order_service::list_my_cust_orders as service_list_my_cust_orders;
use crate::serviceimpl::cust_order_service::get_order_count as service_get_order_count;
use crate::serviceimpl::user_service::find_user_by_id as service_find_user_by_id;
use crate::utils::excel_util::export_excel_workbook_with_image;
use crate::utils::pdf_util::export_pdf_with_images;
use serde::{Deserialize};
use serde_json::{Value,Map};
use std::fs;
use tower_http::{trace::TraceLayer};
use crate::utils::jwt_util;
use crate::utils::jwt_util::Claims;
use crate::utils::jwt_util::JWT_SECRET;
use jsonwebtoken::DecodingKey;
use jsonwebtoken::Validation;
use tower_sessions::Session;
use std::collections::HashMap;

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustOrderListCustRequest {
	pub page: i32,
	pub rows: i32,
}

pub fn cust_order_cust_controller() -> Router {
	Router::new()
	.route("/order_list", post(order_list))
	.layer(DefaultBodyLimit::max(2*1024*1024))
	.layer(TraceLayer::new_for_http())
}

pub async fn order_list(session:Session,Query(params):Query<HashMap<String, String>>,Json(cust_order_list_cust_request):Json<CustOrderListCustRequest>) ->String {
    //let mut user_id = cust_order_list_cust_request.userId;
   	let mut _token:String = "".to_string();
    if let Some(value) = params.get("token") {
        _token = value.clone();
    } else {
        if let Some(session_value) = session.get("token").await.unwrap() {
            _token = session_value;
        }
    }
   	if _token.is_empty() {
      		return r#"{  "rows": null,  "success": false, "error": "请登录后，再提交订单！" }"#.to_string();
   	}
	let claims:Claims = jsonwebtoken::decode(
		&_token,
		&DecodingKey::from_secret(JWT_SECRET.as_bytes()),
		&Validation::default(),
	)
	.map(|data| data.claims).unwrap();
	let user = service_find_user_by_id(claims.sub).await.unwrap();
	let user_id = user.id;

    let pageNumber:i32 = cust_order_list_cust_request.page;
    let pageSize:i32 = cust_order_list_cust_request.rows;
	let cust_orders = service_list_my_cust_orders(user_id).await;

	match cust_orders {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(cust_orders_values) => {
           	let totalCount = cust_orders_values.len();
            let totalPage = (totalCount as f64/pageSize as f64).ceil() as i32;
            let limit = pageSize;
            let start = ((pageNumber -1)*pageSize) as usize;
            let mut end = start + (limit as usize);
            if end > totalCount {
                end = totalCount;
            }
		    let page:Vec<CustOrderBean> = cust_orders_values[start..end].to_vec();
			let json = serde_json::to_string_pretty(&page).unwrap();
			//println!("{}", js
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert("pageNumber".to_string(), Value::from(pageNumber));
			map.insert("pageSize".to_string(), Value::from(pageSize));
			map.insert("totalCount".to_string(), Value::from(totalCount));
			map.insert("totalPage".to_string(), Value::from(totalPage));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}
